package net.lzzy.kvrdd;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class MapGroupBuKeyTest {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf().setAppName("MapToPair").setMaster("local");
        JavaSparkContext jsc = new JavaSparkContext(conf);
        JavaRDD<String> parallelize = jsc.textFile("src\\words.txt");
        JavaRDD<String> javaRDD = parallelize.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String s) throws Exception {
                return Arrays.asList(s.split(" ")).iterator();
            }
        });
        JavaPairRDD<String, Integer> sst = javaRDD.mapToPair(new PairFunction<String, String,Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<>(s.split(" ")[0],1);
            }
        });
        JavaPairRDD<String, Iterable<Integer>> zzt = sst.groupByKey();
        JavaRDD<Tuple2<String, Integer>> map = zzt.map(new Function<Tuple2<String, Iterable<Integer>>, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> call(Tuple2<String, Iterable<Integer>> v1) throws Exception {
                String s = v1._1;
                int val = 0;
                for (Integer integer : v1._2) {
                    val++;
                }
                return new Tuple2<>(s, val);
            }
        });
        List<Tuple2<String, Integer>> collect = map.collect();
        collect.forEach(System.out::println);
    }

}
